# Create your views here.
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response

from .models import User, BankCard, Transaction
from .serializers import UserSerializer, BankCardSerializer, TransactionSerializer

from django.shortcuts import render
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import User
from .serializers import UserSerializer

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password
from django.contrib import messages
from .models import User  # 请根据实际的用户模型进行替换

from django.http import HttpResponse


def login(request):
    return HttpResponse("这是登录页面")


def admin_dashboard(request):
    return HttpResponse("这是管理员仪表盘")


def client_dashboard(request):
    return HttpResponse("这是客户仪表盘")


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        pid = request.POST.get('pid')
        phone = request.POST.get('phone')
        password = request.POST.get('password')

        # 简单验证，可根据需求扩展
        if not all([username, pid, phone, password]):
            return JsonResponse({'success': False, 'message': '请填写所有必填字段'})

        # 检查用户是否已存在
        if User.objects.filter(username=username).exists():
            return JsonResponse({'success': False, 'message': '用户名已存在，请重新输入'})

        # 创建新用户
        new_user = User(
            username=username,
            pid=pid,
            phone=phone,
            password=make_password(password)  # 对密码进行哈希处理
        )
        new_user.save()
        return JsonResponse({'success': True, 'message': '注册成功，请登录'})

    return render(request, 'register.html')


class RegisterView(APIView):
    def post(self, request):
        data = request.data.copy()
        data['password'] = make_password(data['password'])  # 对密码进行哈希处理
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def home(request):
    return render(request, 'index.html')  # 渲染新建的模板def home(request):


# 用户视图：支持查询、修改（需登录）
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

    # 只返回当前登录用户的信息（可选，根据需求调整）
    def get_queryset(self):
        return self.queryset.filter(id=self.request.user.id)


# 银行卡视图：支持增删改查、存款/取款/转账
class BankCardViewSet(viewsets.ModelViewSet):
    queryset = BankCard.objects.all()
    serializer_class = BankCardSerializer
    permission_classes = [permissions.IsAuthenticated]

    # 只返回当前用户的银行卡
    def get_queryset(self):
        return self.queryset.filter(user=self.request.user)

    # 存款操作
    @action(detail=True, methods=["post"])
    def deposit(self, request, pk=None):
        card = self.get_object()
        amount = request.data.get("amount")

        try:
            amount = float(amount)
            if amount <= 0:
                return Response({"detail": "金额必须大于 0"}, status=status.HTTP_400_BAD_REQUEST)

            # 增加余额
            card.balance += amount
            card.save()

            # 记录交易
            Transaction.objects.create(
                card=card,
                transaction_type="DEPOSIT",
                amount=amount,
                operator=request.user.username,
                status="SUCCESS",
                remark="存款操作"
            )

            return Response({
                "detail": "存款成功",
                "balance": card.balance
            })
        except ValueError:
            return Response({"detail": "无效的金额格式"}, status=status.HTTP_400_BAD_REQUEST)

    # 取款操作
    @action(detail=True, methods=["post"])
    def withdraw(self, request, pk=None):
        card = self.get_object()
        amount = request.data.get("amount")
        password = request.data.get("password")

        # 验证密码
        if not request.user.check_password(password):
            return Response({"detail": "密码错误"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            amount = float(amount)
            if amount <= 0:
                return Response({"detail": "金额必须大于 0"}, status=status.HTTP_400_BAD_REQUEST)

            # 检查余额
            if card.balance < amount:
                return Response({"detail": "余额不足"}, status=status.HTTP_400_BAD_REQUEST)

            # 减少余额
            card.balance -= amount
            card.save()

            # 记录交易
            Transaction.objects.create(
                card=card,
                transaction_type="WITHDRAW",
                amount=amount,
                operator=request.user.username,
                status="SUCCESS",
                remark="取款操作"
            )

            return Response({
                "detail": "取款成功",
                "balance": card.balance
            })
        except ValueError:
            return Response({"detail": "无效的金额格式"}, status=status.HTTP_400_BAD_REQUEST)

    # 转账操作
    @action(detail=True, methods=["post"])
    def transfer(self, request, pk=None):
        from_card = self.get_object()
        to_card_number = request.data.get("to_card")
        amount = request.data.get("amount")
        password = request.data.get("password")

        # 验证密码
        if not request.user.check_password(password):
            return Response({"detail": "密码错误"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            amount = float(amount)
            if amount <= 0:
                return Response({"detail": "金额必须大于 0"}, status=status.HTTP_400_BAD_REQUEST)

            # 检查余额
            if from_card.balance < amount:
                return Response({"detail": "余额不足"}, status=status.HTTP_400_BAD_REQUEST)

            # 查找目标银行卡
            try:
                to_card = BankCard.objects.get(card_number=to_card_number)
            except BankCard.DoesNotExist:
                return Response({"detail": "目标银行卡不存在"}, status=status.HTTP_404_NOT_FOUND)

            # 执行转账（原子操作，避免中途出错）
            from_card.balance -= amount
            to_card.balance += amount
            from_card.save()
            to_card.save()

            # 记录转出交易
            Transaction.objects.create(
                card=from_card,
                transaction_type="TRANSFER",
                amount=amount,
                target_card=to_card_number,
                operator=request.user.username,
                status="SUCCESS",
                remark=f"转账至 {to_card_number[-4:]}"
            )

            # 记录转入交易
            Transaction.objects.create(
                card=to_card,
                transaction_type="TRANSFER",
                amount=amount,
                target_card=from_card.card_number,
                operator=request.user.username,
                status="SUCCESS",
                remark=f"来自 {from_card.card_number[-4:]} 的转账"
            )

            return Response({
                "detail": "转账成功",
                "balance": from_card.balance
            })
        except ValueError:
            return Response({"detail": "无效的金额格式"}, status=status.HTTP_400_BAD_REQUEST)


# 交易记录视图：支持查询（需登录）
class TransactionViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = TransactionSerializer
    permission_classes = [permissions.IsAuthenticated]

    # 只返回当前用户银行卡的交易记录
    def get_queryset(self):
        # 获取当前用户的所有银行卡 ID
        card_ids = self.request.user.cards.values_list("id", flat=True)
        # 筛选出这些银行卡的交易记录
        return Transaction.objects.filter(card_id__in=card_ids).order_by("-created_at")
